import { login, logout, getInfo, register } from "@/api/user";
import { getToken, setToken, removeToken } from "@/utils/auth";

const state = {
  token: getToken(),
  username: "",
  name: "",
  phone: "",
  avatar: ""
};

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token;
  },
  SET_NAME: (state, name) => {
    state.name = name;
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar;
  }
};

const actions = {
  register({ commit }, userInfo) {
    const { credential, password, passwordConfirm, phone } = userInfo;
    return new Promise((resolve, reject) => {
      register({
        credential: credential.trim(),
        password: password,
        passwordConfirm: passwordConfirm,
        phone: phone
        // messagecaptcha: messagecaptcha
      })
        .then(response => {
          const { data } = response;
          commit("SET_TOKEN", data);
          setToken(data);
          resolve();
        })
        .catch(error => {
          reject(error);
        });
    });
  },

  // user login
  login({ commit }, userInfo) {
    const { credential, password, messagecaptcha } = userInfo;
    return new Promise((resolve, reject) => {
      login({
        credential: credential.trim(),
        password: password
        // messagecaptcha: messagecaptcha
      })
        .then(response => {
          const { data } = response;
          commit("SET_TOKEN", data);
          setToken(data);
          resolve();
        })
        .catch(error => {
          reject(error);
        });
    });
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo()
        .then(response => {
          const { data } = response;
          if (!data) {
            reject("验证失败, 请重新登录.");
          }
          const { username, photo } = data;
          commit("SET_NAME", username);
          commit("SET_AVATAR", process.env.VUE_APP_BASE_API + "/" + photo);
          resolve(data);
        })
        .catch(error => {
          reject(error);
        });
    });
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout()
        .then(() => {
          commit("SET_TOKEN", "");
          commit("SET_NAME", "");
          removeToken();
          resolve();
        })
        .catch(error => {
          reject(error);
        });
    });
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit("SET_TOKEN", "");
      removeToken();
      resolve();
    });
  }
};

export default {
  namespaced: true,
  state,
  mutations,
  actions
};
